package com.lagou.server.service;

import com.lagou.server.handler.UserServerHandler;
import com.lagou.server.service.dto.*;
import com.lagou.server.service.util.ZookeeperUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现类
 * @author yzh
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    /**
     * 当前服务器的主机地址
     */
    private static String HOST_NAME = "127.0.0.1";

    /**
     * 当前服务器的服务端口号
     */
    private static int PORT = 8001;


    static {
        try {
            //开启服务
            startServer(HOST_NAME, PORT);
            //在zookeeper上注册服务
            registerServer(HOST_NAME, PORT);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Map sayHello(String word) {
        System.out.println("server1调用成功--参数 " + word);
        HashMap<Object, Object> result = new HashMap<>();
        result.put("server", "server1");
        result.put("host", "host1");
        result.put("msg", "server1调用成功--参数 " + word);
        return result;
    }

    /**
     * 启动服务的方法
     * @param hostName
     * @param port
     * @throws InterruptedException
     */
    public static void startServer(String hostName, Integer port) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap
            .group(bossGroup,workerGroup)
            .channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                    pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                    pipeline.addLast(new UserServerHandler());
                }
            });
        serverBootstrap.bind(hostName, port).sync();
    }

    /**
     * 在zookeeper上注册服务的方法
     */
    public static void registerServer(String hostName, int port) {
        //1.连接zookeeper服务端
        ZkClient zkClient = ZookeeperUtil.getZkClient();
        System.out.println("server1 connect zookeeper success");
        //2.生成根节点
        if(!zkClient.exists(ZookeeperUtil.ROOT_PATH)) {
            zkClient.createPersistent(ZookeeperUtil.ROOT_PATH);
        }
        //3.将服务端信息注册到zookeeper中
        if(!zkClient.exists(ZookeeperUtil.ROOT_PATH + "/host1")) {
            zkClient.createPersistent(ZookeeperUtil.ROOT_PATH + "/host1", "");
        }
        zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/host1/hostname", hostName);
        zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/host1/port", port);
        zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/host1/status", "running");
        System.out.println("server1 register success");
    }

}
